import json
from lib.api import iot
from lib.sensors.soil import LM393
from lib.config.index import sensor_config
from lib.sensors.ssd1306.oled import OLED

config = sensor_config.get_sensor("LM393")
print(config)
A0 = config["A0"]
D0 = config["D0"]


config = sensor_config.get_sensor("ssd1306")
# print(config)
scl = config["scl"]
sda = config["sda"]

f = open("/lib/sensors/oled/fonts/fonts_12.json", "r")
data = f.read()
fonts = json.loads(data)
f.close()


_oled = OLED(scl, sda)
_oled.font_renderer.set_font(fonts, 12)
_oled.font_renderer.reset_line()
_oled.font_renderer.show_text("开始测量数据...")


soil = LM393.Soil(A0, D0)


def demo():
    global _oled
    import time

    while True:
        v = soil.read_analog()
        hu = round(100 - v / 40.96, 2)
        time.sleep(3)
        payload = {"humidity": hu, "value": v}
        print(payload)
        iot.upload_data(payload, "Tiot_xtbrkh2t")
        _oled.clear()
        _oled.font_renderer.auto_text(f"湿度: {hu}%", 0, 0, 12)


if __name__ == "__main__":
    demo()
